package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryType() {
        // 从redis中查询所有商铺类型
        String jsonStr = stringRedisTemplate.opsForValue().get("shop:type:list");
        List<ShopType> typeList = JSONUtil.toList(jsonStr, ShopType.class);
        if(typeList != null && typeList.size() > 0 ){
            // 查到直接返回
            return Result.ok(typeList);
        }
        // 查不到去数据库里查
        typeList = query().orderByAsc("sort").list();
        // 数据库里没有报错
        if (typeList == null){
            return Result.fail("店铺不存在！");
        }
        // 有就存到redis中最后返回
        // 将一个数组存到redis中
        stringRedisTemplate.opsForValue().set("shop:type:list", JSONUtil.toJsonStr(typeList));

        return Result.ok(typeList);
    }
}
